
#include <iostream>

#include <boost/bind.hpp>

#include "server/Server.hpp"
#include "server/Session.hpp"

using namespace Fxt::Server;

Session::Session(Server & server) :
	_server(server),
	_socket(server.ios())
{

}

Session::~Session() {

}

void Session::start() {
	std::cout << "Starting session" << std::endl;
	this->_startRead();
}

void Session::_startRead() {
	std::cout << "Waiting for data to read" << std::endl;
	this->_socket.async_read_some(
		boost::asio::buffer(this->_buffer, bufferSize),
		boost::bind(&Session::_handleRead,this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)
	);
}

void Session::_handleRead(boost::system::error_code const & error, std::size_t bytesTransferred) {
	if (error) {
		std::cout << "Error reading (error code: " << error << ")" << std::endl;
		this->_server.sessionClosed();
	} else {
		std::cout << "Data received: " << std::string(this->_buffer, bytesTransferred) << std::endl;
		this->_startRead();
	}
}

boost::asio::ip::tcp::socket & Session::socket() {
	return this->_socket;
}
